package org.ytor.core.sysapi.file.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.ytor.common.model.R;
import org.ytor.core.BaseController;
import org.ytor.core.DownloadMapper;
import org.ytor.core.querygen.WhereGenerator;
import org.ytor.core.sqlflow.Page;
import org.ytor.core.sqlflow.builder.support.WhereBuilder;
import org.ytor.core.sysapi.file.logic.SysFileLogic;
import org.ytor.core.sysapi.file.model.SysFile;
import org.ytor.core.sysapi.file.repository.SysFileRepository;
import org.ytor.core.sysapi.file.req.SysFileReq;
import org.ytor.core.sysapi.file.resp.SysFileResp;
import org.ytor.core.util.Pages;

/**
 * created by yangtong on 2025/4/8 16:45:39
 * <br/>
 * 文件系统接口
 */
@RestController
@RequestMapping("/sys/file")
@Tag(name = "文件")
public class SysFileController extends BaseController<SysFile, SysFileLogic, SysFileRepository> {

    /**
     * 分页查询
     */
    @GetMapping("page")
    @Operation(summary = "分页查询", description = "分页查询")
    public R<Page<SysFileResp>> page(@ParameterObject SysFileReq fileReq) {
        WhereBuilder where = WhereGenerator.where();
        Page<SysFile> page = repository.queryPage(where);
        return R.success(Pages.transPage(page, SysFile::toResp));
    }

    /**
     * 上传文件
     */
    @PostMapping("upload")
    @Operation(summary = "上传文件", description = "上传文件")
    public R<String> upload(@RequestPart MultipartFile file) {
        String fileId = logic.upload(file);
        return R.success(fileId);
    }

    /**
     * 根据文件id删除文件
     */
    @DeleteMapping("delete")
    @Operation(summary = "根据文件id删除文件", description = "根据文件id删除文件")
    public R<String> delete(String fileId) {
        logic.delete(fileId);
        return R.success("删除成功");
    }

    /**
     * 下载文件
     */
    @ApiResponse(
            responseCode = "200",
            description = "文件下载成功",
            content = @Content(
                    mediaType = "application/octet-stream",
                    schema = @Schema(type = "string", format = "binary")
            )
    )
    @Operation(summary = "下载文件", description = "下载文件")
    @DownloadMapper(value = "download")
    public void download(String fileId) {
        logic.download(fileId);
    }

}
